from requests.packages.urllib3.exceptions import InsecureRequestWarning

# !usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: lenovo by amidoufu
@file: amidoufu.py
@time: 2020/05/06
@function: 
"""
import requests
import json
import time
import os
import webbrowser
import re
import emoji
import ssl
import fileinput
import sys
import random
import threading
import pygame
import configparser
import tkinter.messagebox
from tkinter import *
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from requests.packages.urllib3.exceptions import InsecureRequestWarning

ssl._create_default_https_context = ssl._create_unverified_context

INFO = {
    "name": "奥利给丶快手批量下载助手",
    "author": "阿米豆腐丶",
    "repository": "最初版本oGsLP提供,最初源码下载地址:www.github.com/oGsLP/kuaishou-crawler",
    "version": "0.2",
    "publishDate": "20-05-06"
}

PROFILE_URL = "https://live.kuaishou.com/profile/"
DATA_URL = "https://live.kuaishou.com/m_graphql"
WORK_URL = "https://v.kuaishou.com/fw/photo/"
MUSIC_URL = "https://v.kuaishou.com/rest/kd/tag/feed/music"
TEXT_URL =  "https://v.kuaishou.com/rest/kd/tag/feed/text"




__param_did = ""

__headers_web = {
    'accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
    'Connection': 'keep-alive',
    'Content-Type': 'application/json',
    'Host': 'live.kuaishou.com',
    'Origin': 'https://live.kuaishou.com',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    # User-Agent/Cookie 根据自己的电脑修改
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
    'Cookie': ''
}
__headers_mobile = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',#'*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',#'close',
    'Host': 'v.kuaishou.com',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'none',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': '',
    'Cookie': ''
}
__headers_Requests_web = {
    'accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
    'Connection': 'keep-alive',
    'Host': 'v.kuaishou.com',
    'Upgrade-Insecure-Requests': '1',
    # User-Agent/Cookie 根据自己的电脑修改
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
    'Cookie': ''
}
# User-Agent': 'Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36

class QJ:
    exists = 0
    stop = False
    userid_cook = ""
    sid_cook = ""
    current_uid = ""
    video_num = 0
    uid_jici = 0
    yzm_num = 0
    ua_list_ = ""
    bak_uid = ""
    find_url1_last = ""
    find_url2_last = ""
    find_url3_last = ""
    cookie_mobile = ""
    duanlian = ""
    duanlian_list = []
    uid_list_num = 0
    zhuangtaima = ""
    dkkm = ""
    jiqima = ""
    jiance_uid = 0
    uid_list_zongshu_bak = 0
    __doufu_list_jiance = []
    doufu_list__ = []
    bakuid = ""
    bakname = ""
    cookie1 = ""
    cookie2 = ""
    cookie3 = ""
    cookie4 = ""
    cookie5 = ""
    mdl = 0
    pass_uid = ""


ua_list = ['Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+','Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263','Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263','Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36','Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+','Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36','Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)','Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13','Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1','Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53','Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1','Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1','Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1','Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1','Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1','Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1']
exists = 0
click_access = 0
xiladaili = ""
__doufu_list = []

__date_cache = ""
__date_pic_count = 0



def __init__():
    if QJ.userid_cook != "":
        thread_it(doufu(),)
    else:
        thread_it(__intro(),)

def set_did(did, did2, did3, did4, did5):
    __param_did = did
    # __param_did1 = did1
    __param_did2 = did2
    __param_did3 = did3
    __param_did4 = did4
    __param_did5 = did5
    # __param_did3 = did3
    options = webdriver.ChromeOptions()
    options.add_argument(
        'User-Agent=' + QJ.ua_list_)
    driver = webdriver.Chrome(executable_path="Google Chrome/chromedriver.exe", chrome_options=options)
    driver.get(QJ.duanlian)
    # driver.implicitly_wait(30)
    file = '提示音.wav'  # 文件名是完整路径名
    iframes = driver.find_elements_by_tag_name("iframe")
    while iframes != []:
        # driver.implicitly_wait(30)
        text.insert(END, "出现验证码弹窗请手动验证")
        text.update()
        text.see(END)
        pygame.mixer.init()  # 初始化音频
        track = pygame.mixer.music.load(file)  # 载入音乐文件
        pygame.mixer.music.play()  # 开始播放
        time.sleep(3)
        pygame.mixer.music.stop()  # 停止播放
        iframes = driver.find_elements_by_tag_name("iframe")
        if iframes == []:
            pygame.mixer.music.stop()  # 停止播放
            break
    cookie5 = [item['name'] + '=' + item['value'] for item in driver.get_cookies()]
    cookie3 = [item['name'] for item in driver.get_cookies()]
    cookie4 = [item['value'] for item in driver.get_cookies()]
    sep = "; "
    QJ.cookie_mobile = sep.join(cookie5)
    for cookie3_jici in range(len(cookie3)):
        if cookie3[cookie3_jici] == "sid":
            QJ.sid_cook = cookie4[cookie3_jici]
            break
    url_ = driver.current_url
    find_url_1 = 'fid=(.*?)&photoId='
    find_url_2 = '&shareId=(.*?)&userId='
    find_url_3 = '&shareType=(.*?)&timestamp='
    find_url1 = re.findall(find_url_1, url_)
    find_url2 = re.findall(find_url_2, url_)
    find_url3 = re.findall(find_url_3, url_)
    QJ.find_url1_last = find_url1[0]
    QJ.find_url2_last = find_url2[0]
    QJ.find_url3_last = find_url3[0]
    driver.close()
    __headers_web[
        'Cookie'] = 'did=' + did + ';userId=' + did5 + ';kuaishou.live.web_st=' + did2 + ';kuaishou.live.web_ph=' + did3 + ';kuaishou.live.bfb1s=' + did4
    __headers_mobile['Cookie'] = QJ.cookie_mobile#'did=' + did + ';userId=' + did5 + ';didv=' + str(int(time.time()) * 1000) + ';sid=' + QJ.sid_cook
    # text.insert(END,"初始化成功...")
    # text.update()
    # text.see(END)
    text.insert(END, "用户cookie的值：" + 'did=' + did + ';userId=' + did5 + ';kuaishou.live.web_st=' + did2 + ';kuaishou.live.web_ph=' + did3 + ';kuaishou.live.bfb1s=' + did4)
    text.update()
    text.see(END)
    if click_access != 1:
        thread_it(doufu(), )
    else:
        thread_it(one_click_access2(), )
    # __headers_web['Cookie'] = 'did=' + did + ';kuaishou.live.web_ph=' + did1 + ';kuaishou.live.web_st=' + did2 + ';kuaishou.live.bfb1s=' + did3 +';didv=' + str(int(time.time())*1000) + ';userId='
    # __headers_mobile['Cookie'] = 'did=' + did + ';kuaishou.live.web_ph=' + did1 + ';kuaishou.live.web_st=' + did2 + ';kuaishou.live.bfb1s=' + did3 +';didv=' + str(int(time.time())*1000) + ';userId='




def doufu():
    latetime = int(entry.get())
    text.insert(END, "")
    text.update()
    text.see(END)
    text.insert(END,"延时时间:" + str(latetime))
    text.update()
    text.see(END)
    text.insert(END, "")
    text.update()
    text.see(END)
    text.insert(END,"准备开始爬取喜欢列表...")
    text.update()
    text.see(END)
    time.sleep(3)
    __doufu_user(QJ.pass_uid, latetime)


def add_to_list(uid):
    QJ.doufu_list__.append(uid)

def add_to_list2(uid):
    QJ.__doufu_list_jiance.append(uid)

def chongxinduqu_uid():
    QJ.__doufu_list_jiance = []
    p_path2 = "uid.txt"
    with open(p_path2, "r") as f2:
        for line2 in f2:
            if line2[0] != "#":
                QJ.__doufu_list_jiance.append(line2.strip())
    if len(QJ.__doufu_list_jiance) != QJ.uid_list_zongshu_bak:
        QJ.jiance_uid = 1
        QJ.doufu_list__ = []
        new_uid_list = tkinter.messagebox.askokcancel('提示', 'uid.txt有更新,请问是否重新获取uid列表!!!')
        if new_uid_list == True:
            doufu()


def __doufu_user(uid, latetime):
    if uid.isdigit():
        uid = __switch_id(uid)

    pcursor = ""
    page = 1
    payload = {"operationName": "likedFeedsQuery",
               "variables": {"principalId": QJ.pass_uid, "pcursor": "", "count": 99},
               "query": "query likedFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  likedFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
    res = requests.post(DATA_URL, headers=__headers_web, json=payload)
    # print(uid)
    # print(res.text)
    works = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['likedFeeds']['list']
    # print(works)
    pcursor = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['likedFeeds']['pcursor']
    #print(pcursor)
    if works != []:
        if not os.path.exists("./快手喜欢data"):
            os.makedirs("./快手喜欢data")

        # 这两行代码将response写入json供分析
        # with open("data/" + uid + ".json", "w") as fp:
        #     fp.write(json.dumps(works, indent=2))

        # 防止该用户在直播，第一个作品默认为直播，导致获取信息为NoneType
        # print(works)
        # if works[0]['id'] is None:
        #     works.pop(0)
        name = re.sub(r'[\\/:*?"<>|\r\n]+', "", uid)

        # eid = re.sub(r'[\\/:*?"<>|\r\n]+', "", works[0]['userEid'])
        # usename = re.sub(r'[\\/:*?"<>|\r\n]+', "", works[0]['userName'])
        dir = "快手喜欢列表data/" + name + "/"
        # print(len(works))
        if not os.path.exists(dir):
            os.makedirs(dir)

        # music_url = works[0]['music']['audioUrls'][0]['url']
        # # print(music_url)
        # music_music = dir + name + ".m4a"
        # if not os.path.exists(music_music):
        #     r = requests.get(music_url)
        #     r.raise_for_status()
        #
        #     with open(music_music, "wb") as f:
        #         f.write(r.content)
        #     print(name + "音乐下载成功 √")
        text.insert(END, '第%s页喜欢视频地址获取成功\n' % (page))
        text.update()
        text.see(END)
        while pcursor != "no_more":
            page += 1
            payload = {"operationName": "likedFeedsQuery",
                       "variables": {"principalId": QJ.pass_uid, "pcursor": pcursor, "count": 99},
                       "query": "query likedFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  likedFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
            res = requests.post(DATA_URL, headers=__headers_web, json=payload)
            works = works + json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['likedFeeds']['list']
            pcursor = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['likedFeeds']['pcursor']
            text.insert(END, '第%s页喜欢视频地址获取成功\n' % (page))
            text.update()
            text.see(END)
        text.insert(END, "开始爬取喜欢 " + name + ",保存在目录丨" + dir)
        text.update()
        text.see(END)
        text.insert(END, " 共有" + str(len(works)) + "个作品")
        text.update()
        text.see(END)
        text.insert(END, "")
        text.update()
        text.see(END)
        time.sleep(1)
        for j in range(len(works)):
            __doufu_work(uid, dir, works[j], j + 1)
            if not os.path.exists(dir + "图集/"):
                photos = 0
            else:
                photos = len([lists for lists in os.listdir(dir + "图集/") if
                              os.path.isdir(os.path.join(dir + "图集/", lists))])

            if not os.path.exists(dir + "视频/"):
                videos = 0
            else:
                videos = len([lists for lists in os.listdir(dir + "视频/") if
                              os.path.isfile(os.path.join(dir + "视频/", lists))])

            allnumber = photos + videos
            text.insert(END, "丨用户:" + name + "丨" + "UID:" + uid + "丨第:" + str(QJ.uid_list_num + 1) + "个用户丨")
            text.update()
            text.see(END)
            text.insert(END, "丨下载信息如下:丨")
            text.update()
            text.see(END)
            text.insert(END, "丨总下载数:" + str(len(works)) + "个丨" + "当前下载数:" + str(j + 1) + "个丨" + "等待下载数:" + str(
                len(works) - j - 1) + "个丨")
            text.update()
            text.see(END)
            text.insert(END, "丨当前电脑共有作品数:" + str(allnumber) + "个丨视频:" + str(videos) + "个丨图集:" + str(photos) + "个丨")
            text.update()
            text.see(END)
            time.sleep(int(latetime))
            text.insert(END, "")
            text.update()
            text.see(END)

    allnumber = photos + videos
    text.insert(END, "")
    text.update()
    text.see(END)
    text.insert(END, "丨用户:" + name + "丨")
    text.update()
    text.see(END)
    text.insert(END, "丨当前电脑共有作品数:" + str(allnumber) + "个丨视频:" + str(videos) + "个丨图集:" + str(photos) + "个丨")
    text.update()
    text.see(END)
    text.insert(END, "")
    text.update()
    text.see(END)
    text.insert(END, "用户 " + name + "视频爬取完成!")
    text.update()
    text.see(END)
    text.insert(END, "")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待3秒退出")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待2秒退出")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待1秒退出")
    text.update()
    text.see(END)
    time.sleep(1)
    exit()


    # lines = [l for l in open("biaoqianhuati.txt", "r") if l.find(uid, 0, 8) != 0]
    # fd = open("biaoqianhuati_log.txt", "w")
    # fd.writelines(lines)
    # fd.close()

    # print(path_list)

    # with open("a.txt", "r+") as f:
    #     p = re.compile("gmail|aol|yahoo")
    #     lines = [line for line in f.readlines() if p.search(line) is None]
    #     f.seek(0)
    #     f.truncate(0)
    #     f.writelines(lines)

    # list = []
    # matchPattern = re.compile(uid)
    # f_path = r'biaoqianhuati.txt'
    # with open(f_path)as f:
    #     while 1:
    #         line = f.readline()
    #         if not line:
    #             break
    #         elif matchPattern.search(line):
    #             pass
    #         else:
    #             list.append(line)
    #     f.close()
    #     f = open('biaoqianhuati_log.txt', 'w')
    #     for i in list:
    #         f.write(i)
    #     f.close()

    '''
    快手分为五种类型的作品，在作品里面表现为workType属性
     * 其中两种图集: `vertical`和`multiple`，意味着拼接长图和多图，所有图片的链接在imgUrls里
     * 一种单张图片: `single` 图片链接也在imgUrls里
     * K歌: `ksong` 图片链接一样，不考虑爬取音频...
     * 视频: `video` 需要解析html获得视频链接
    '''


def __doufu_work(uid, dir, work, wdx):
    w_type = work['workType']
    w_caption = re.sub(r"\s+", " ", work['caption'])
    w_name2 = re.sub(r'[\\/:*?"<>|\r\n]+', "", w_caption)[0:24]
    emoji_str = emoji.demojize(w_name2)
    w_name = re.sub(r':(.*?):', '', emoji_str).strip()
    w_time = time.strftime('%Y年%m月%d日%H时%M分%S秒', time.localtime(work['timestamp'] / 1000))
    w_time_old = time.strftime('%Y-%m-%d', time.localtime(work['timestamp'] / 1000))
    w_index = ""
    global __date_cache
    global __date_count
    if __date_cache == w_time:
        __date_count = __date_count + 1
        if __date_count > 0:
            w_index = "(%d)" % __date_count
    else:
        __date_cache = w_time
        __date_count = 0

    if w_type == 'vertical' or w_type == 'multiple' or w_type == "single" or w_type == 'ksong':
        if var7.get() == 0:
            w_name2 = re.sub(r'[.*?"<>|\r\n]+', "", w_name)
            tuji_name = w_time + "_" + work['id'] + "_" + w_name2
            tuji_lujing = dir + "图集/"
            tuji = tuji_lujing + tuji_name
            if not os.path.exists(tuji_lujing):
                tuji_list = []
            else:
                tuji_list = os.listdir(tuji_lujing)

            for tuji_jici in range(len(tuji_list)):
                if w_time in tuji_list[tuji_jici]:
                    text.insert(END, "    图集 " + tuji_name + " 已存在 √")
                    text.update()
                    text.see(END)
                    text.insert(END, "丨图集已存在 √丨")
                    text.update()
                    text.see(END)
                    QJ.exists += 1
                    #print(QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                    yichuxiancishu["text"] = "用户:" + QJ.bakname + ",UID:" + QJ.bakuid + ",已存在" + str(QJ.exists) + "次"
                    text.insert(END, "丨" + QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次" + "丨")
                    text.update()
                    text.see(END)
                    break
                elif w_time_old in tuji_list[tuji_jici]:
                    text.insert(END, "    图集 " + tuji_name + " 已存在 √")
                    text.update()
                    text.see(END)
                    text.insert(END, "丨图集已存在 √丨")
                    text.update()
                    text.see(END)
                    QJ.exists += 1
                    #print(QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                    yichuxiancishu["text"] = "用户:" + QJ.bakname + ",UID:" + QJ.bakuid + ",已存在" + str(QJ.exists) + "次"
                    text.insert(END, "丨"  + QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次" + "丨" )
                    text.update()
                    text.see(END)
                    break

                        # text.insert(END, QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                        # text.update()
                        # text.see(END)
            else:
                QJ.exists = 0
                w_urls = work['imgUrls']
                l = len(w_urls)
                text.insert(END, "  " + str(wdx) + ")图集作品：" + w_caption + "，" + "共有" + str(l) + "张图片")
                text.update()
                text.see(END)
                for i in range(l):
                    p_name = w_time + "_" + work['id'] + "_" + w_name + "_" + str(i + 1) + '.jpg'
                    w_name2 = re.sub(r'[.*?"<>|\r\n]+', "", w_name)
                    dir2 = dir + "图集/" + w_time + "_" + work['id'] + "_" + w_name2 + "/"
                    if not os.path.exists(dir2):
                        os.makedirs(dir2)
                    pic = dir2 + p_name
                    if not os.path.exists(pic):
                        while True:  # 一直循环，知道访问站点成功
                            try:
                                # 以下except都是用来捕获当requests请求出现异常时，
                                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                r = requests.get(w_urls[i].replace("webp", "jpg"), verify=False)
                                r.raise_for_status()
                                break
                            except requests.exceptions.HTTPError:
                                text.insert(END, "HTTPError, 等待60秒后程序重新运行!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()
                            except requests.exceptions.ConnectionError:
                                text.insert(END, "ConnectionError, 等待60秒后程序重新运行!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()
                            except requests.exceptions.ChunkedEncodingError:
                                text.insert(END, "ChunkedEncodingError, 等待60秒后程序重新运行!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()
                            except:
                                text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()

                        with open(pic, "wb") as f:
                            f.write(r.content)
                        text.insert(END, "    " + str(i + 1) + "/" + str(l) + " 图片 " + p_name + " 下载成功 √")
                        text.update()
                        text.see(END)
                        text.insert(END, "图集地址:")
                        text.update()
                        text.see(END)
                        text.insert(END, w_urls[i])
                        text.update()
                        text.see(END)
                        text.insert(END, "丨图片下载成功 √丨")
                        text.update()
                        text.see(END)
                    else:
                        text.insert(END, "    " + str(i + 1) + "/" + str(l) + " 图片 " + p_name + " 已存在 √")
                        text.update()
                        text.see(END)
                        text.insert(END, "丨图片已存在 √丨")
                        text.update()
                        text.see(END)
    elif w_type == 'video':
        if var3.get() == 0:
            v_name = w_time + "_" + work['id'] + "_" + w_name + ".mp4"
            dir2 = dir + "视频/"
            video = dir2 + v_name
            if not os.path.exists(dir2):
                video_list = []
            else:
                video_list = os.listdir(dir2)
            for video_jici in range(len(video_list)):
                if w_time in video_list[video_jici]:
                    text.insert(END, "    视频 " + v_name + " 已存在 √")
                    text.update()
                    text.see(END)
                    text.insert(END, "丨视频已存在 √丨")
                    text.update()
                    text.see(END)
                    QJ.exists += 1
                    #print(QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                    yichuxiancishu["text"] = "用户:" + QJ.bakname + ",UID:" + QJ.bakuid + ",已存在" + str(QJ.exists) + "次"
                    text.insert(END, "丨" + QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次" + "丨")
                    text.update()
                    text.see(END)
                    break
                elif w_time_old in video_list[video_jici]:
                    text.insert(END, "    视频 " + v_name + " 已存在 √")
                    text.update()
                    text.see(END)
                    text.insert(END, "丨视频已存在 √丨")
                    text.update()
                    text.see(END)
                    QJ.exists += 1
                    #print(QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                    yichuxiancishu["text"] = "用户:" + QJ.bakname + ",UID:" + QJ.bakuid + ",已存在" + str(QJ.exists) + "次"
                    text.insert(END, "丨" + QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次" + "丨")
                    text.update()
                    text.see(END)
                    break
                        # text.insert(END, QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
                        # text.update()
                        # text.see(END)
            else:
                QJ.exists = 0
                w_url = WORK_URL + work['id'] + "?fid=" + QJ.find_url1_last + "&photoId=" + work['id'] + "&shareId=" + QJ.find_url2_last + "&userId=" + QJ.bak_uid + "&shareType=" + QJ.find_url3_last + "&timestamp=" + str(int(round(time.time() * 1000)))
                while True:  # 一直循环，知道访问站点成功
                    try:
                        # 以下except都是用来捕获当requests请求出现异常时，
                        # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                        res = requests.get(w_url, headers=__headers_mobile, verify=False)
                        res.raise_for_status()
                        break
                    except requests.exceptions.HTTPError:
                        text.insert(END, "HTTPError, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                    except requests.exceptions.ConnectionError:
                        text.insert(END, "ConnectionError, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                    except requests.exceptions.ChunkedEncodingError:
                        text.insert(END, "ChunkedEncodingError, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                    except:
                        text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                #requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

                # payload1 = {"operationName": "SharePageQuery",
                #            "variables": {"photoId": work['id'], "principalId": uid},
                #            "query": "query SharePageQuery($principalId: String, $photoId: String) {\n  feedById(principalId: $principalId, photoId: $photoId) {\n    currentWork {\n      playUrl\n      __typename\n    }\n    __typename\n  }\n}\n"}
                # res1 = requests.post(DATA_URL, headers=__headers_web, json=payload1)
                # html1 = json.loads(res1.content.decode(encoding='utf-8', errors='strict'))['data']['feedById']['currentWork']
                # v_url = html1['playUrl']

                html = res.text
                waitreplace2 = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'
                v_url2 = re.findall(waitreplace2, html)
                if v_url2 == []:
                    waitreplace = '"srcNoMark":"(.*?)"},"user"'
                else:
                    waitreplace = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'


                yzm_jici = 0
                while html.find('操作太快了，请稍微休息一下') != -1:
                    text.insert(END, "出现操作太快了!!!可能触发反爬机制------60秒后再次重新打开浏览器获取cook!!!")
                    text.update()
                    text.see(END)
                    QJ.ua_list_ = ua_list[random.randint(0, 28)]
                    text.insert(END, "定义浏览器移动端标识(User-Agent):" + QJ.ua_list_)
                    text.update()
                    text.see(END)
                    __headers_mobile[
                        'Cookie'] = ''  # 'did=' + did + ';userId=' + did5 + ';didv=' + str(int(time.time()) * 1000) + ';sid=' + QJ.sid_cook
                    time.sleep(60)
                    options = webdriver.ChromeOptions()
                    options.add_argument(
                        'User-Agent=' + QJ.ua_list_)
                    driver = webdriver.Chrome(executable_path="Google Chrome/chromedriver.exe", chrome_options=options)
                    if len(QJ.duanlian_list) == 1:
                        QJ.duanlian = QJ.duanlian_list[0]
                    else:
                        QJ.duanlian = QJ.duanlian_list[random.randint(0, len(QJ.duanlian_list) - 1)]
                    text.insert(END, "当前选择的分享短链:" + QJ.duanlian)
                    text.update()
                    text.see(END)
                    driver.get(QJ.duanlian)
                    #driver.implicitly_wait(30)
                    file = '提示音.wav'  # 文件名是完整路径名
                    iframes = driver.find_elements_by_tag_name("iframe")
                    while iframes != []:
                        # driver.implicitly_wait(30)
                        text.insert(END, "出现验证码弹窗请手动验证")
                        text.update()
                        text.see(END)
                        pygame.mixer.init()  # 初始化音频
                        track = pygame.mixer.music.load(file)  # 载入音乐文件
                        pygame.mixer.music.play()  # 开始播放
                        time.sleep(3)
                        pygame.mixer.music.stop()  # 停止播放
                        iframes = driver.find_elements_by_tag_name("iframe")
                        if iframes == []:
                            pygame.mixer.music.stop()  # 停止播放
                            break
                    cookie5 = [item['name'] + '=' + item['value'] for item in driver.get_cookies()]
                    cookie3 = [item['name'] for item in driver.get_cookies()]
                    cookie4 = [item['value'] for item in driver.get_cookies()]
                    sep = "; "
                    QJ.cookie_mobile = sep.join(cookie5)
                    for cookie3_jici in range(len(cookie3)):
                        if cookie3[cookie3_jici] == "sid":
                            QJ.sid_cook = cookie4[cookie3_jici]
                            break
                    driver.close()
                    __headers_mobile[
                        'Cookie'] = QJ.cookie_mobile  # 'did=' + did + ';userId=' + did5 + ';didv=' + str(int(time.time()) * 1000) + ';sid=' + QJ.sid_cook
                    w_url = WORK_URL + work['id'] + "?fid=" + QJ.find_url1_last + "&photoId=" + work['id'] + "&shareId=" + QJ.find_url2_last + "&userId=" + QJ.bak_uid + "&shareType=" + QJ.find_url3_last + "&timestamp=" + str(int(round(time.time() * 1000)))
                    while True:  # 一直循环，知道访问站点成功
                        try:
                            # 以下except都是用来捕获当requests请求出现异常时，
                            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                            res = requests.get(w_url, headers=__headers_mobile, verify=False)
                            res.raise_for_status()
                            break
                        except requests.exceptions.HTTPError:
                            text.insert(END, "HTTPError, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                        except requests.exceptions.ConnectionError:
                            text.insert(END, "ConnectionError, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                        except requests.exceptions.ChunkedEncodingError:
                            text.insert(END, "ChunkedEncodingError, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                        except:
                            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                    # w_url = WORK_URL + work['id']
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False,
                    #                    params={"fid": int(QJ.userid_cook), "cc": "share_copylink",
                    #                            "shareId": "143108986354"})

                    #requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

                    # payload1 = {"operationName": "SharePageQuery",
                    #            "variables": {"photoId": work['id'], "principalId": uid},
                    #            "query": "query SharePageQuery($principalId: String, $photoId: String) {\n  feedById(principalId: $principalId, photoId: $photoId) {\n    currentWork {\n      playUrl\n      __typename\n    }\n    __typename\n  }\n}\n"}
                    # res1 = requests.post(DATA_URL, headers=__headers_web, json=payload1)
                    # html1 = json.loads(res1.content.decode(encoding='utf-8', errors='strict'))['data']['feedById']['currentWork']
                    # v_url = html1['playUrl']

                    html = res.text
                    waitreplace2 = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'
                    v_url2 = re.findall(waitreplace2, html)
                    if v_url2 == []:
                        waitreplace = '"srcNoMark":"(.*?)"},"user"'
                    else:
                        waitreplace = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'
                    yzm_jici = yzm_jici + 1
                    if yzm_jici == QJ.yzm_num:
                        restart_program()


                    # payload1 = {"operationName": "SharePageQuery",
                    #            "variables": {"photoId": work['id'], "principalId": uid},
                    #            "query": "query SharePageQuery($principalId: String, $photoId: String) {\n  feedById(principalId: $principalId, photoId: $photoId) {\n    currentWork {\n      playUrl\n      __typename\n    }\n    __typename\n  }\n}\n"}
                    # res1 = requests.post(DATA_URL, headers=__headers_web, json=payload1)
                    # html1 = json.loads(res1.content.decode(encoding='utf-8', errors='strict'))['data']['feedById']['currentWork']
                    # v_url = html1['playUrl']

                    # doufu()

                # if html.find('快手验证码') != -1:
                #     text.insert(END, "出现验证码了!!!可能触发反爬机制------60秒后程序自动重新运行!!!")
                #     text.update()
                #     text.see(END)
                #     time.sleep(60)
                #     restart_program()
                yzm_jici1 = 0
                while html.find('快手验证码') != -1:
                    text.insert(END, "出现验证码了!!!可能触发反爬机制------60秒后再次重新打开浏览器获取cook!!!")
                    text.update()
                    text.see(END)
                    QJ.ua_list_ = ua_list[random.randint(0, 28)]
                    text.insert(END, "定义浏览器移动端标识(User-Agent):" + QJ.ua_list_)
                    text.update()
                    text.see(END)
                    __headers_mobile[
                        'Cookie'] = ''  # 'did=' + did + ';userId=' + did5 + ';didv=' + str(int(time.time()) * 1000) + ';sid=' + QJ.sid_cook
                    time.sleep(60)
                    options = webdriver.ChromeOptions()
                    options.add_argument(
                        'User-Agent=' + QJ.ua_list_)
                    driver = webdriver.Chrome(executable_path="Google Chrome/chromedriver.exe", chrome_options=options)
                    if len(QJ.duanlian_list) == 1:
                        QJ.duanlian = QJ.duanlian_list[0]
                    else:
                        QJ.duanlian = QJ.duanlian_list[random.randint(0, len(QJ.duanlian_list) - 1)]
                    text.insert(END, "当前选择的分享短链:" + QJ.duanlian)
                    text.update()
                    text.see(END)
                    driver.get(QJ.duanlian)
                    #driver.implicitly_wait(30)
                    file = '提示音.wav'  # 文件名是完整路径名
                    iframes = driver.find_elements_by_tag_name("iframe")
                    while iframes != []:
                        # driver.implicitly_wait(30)
                        text.insert(END, "出现验证码弹窗请手动验证")
                        text.update()
                        text.see(END)
                        pygame.mixer.init()  # 初始化音频
                        track = pygame.mixer.music.load(file)  # 载入音乐文件
                        pygame.mixer.music.play()  # 开始播放
                        time.sleep(3)
                        pygame.mixer.music.stop()  # 停止播放
                        iframes = driver.find_elements_by_tag_name("iframe")
                        if iframes == []:
                            pygame.mixer.music.stop()  # 停止播放
                            break
                    cookie5 = [item['name'] + '=' + item['value'] for item in driver.get_cookies()]
                    cookie3 = [item['name'] for item in driver.get_cookies()]
                    cookie4 = [item['value'] for item in driver.get_cookies()]
                    sep = "; "
                    QJ.cookie_mobile = sep.join(cookie5)
                    for cookie3_jici in range(len(cookie3)):
                        if cookie3[cookie3_jici] == "sid":
                            QJ.sid_cook = cookie4[cookie3_jici]
                            break
                    driver.close()
                    __headers_mobile[
                        'Cookie'] = QJ.cookie_mobile  # 'did=' + did + ';userId=' + did5 + ';didv=' + str(int(time.time()) * 1000) + ';sid=' + QJ.sid_cook
                    w_url = WORK_URL + work['id'] + "?fid=" + QJ.find_url1_last + "&photoId=" + work['id'] + "&shareId=" + QJ.find_url2_last + "&userId=" + QJ.bak_uid + "&shareType=" + QJ.find_url3_last + "&timestamp=" + str(int(round(time.time() * 1000)))
                    while True:  # 一直循环，知道访问站点成功
                        try:
                            # 以下except都是用来捕获当requests请求出现异常时，
                            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                            res = requests.get(w_url, headers=__headers_mobile, verify=False)
                            res.raise_for_status()
                            break
                        except requests.exceptions.HTTPError:
                            text.insert(END, "HTTPError, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                        except requests.exceptions.ConnectionError:
                            text.insert(END, "ConnectionError, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                        except requests.exceptions.ChunkedEncodingError:
                            text.insert(END, "ChunkedEncodingError, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                        except:
                            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                            text.update()
                            text.see(END)
                            time.sleep(60)
                            restart_program()
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                    # w_url = WORK_URL + work['id']
                    # res = requests.get(w_url, headers=__headers_mobile, verify=False,
                    #                    params={"fid": int(QJ.userid_cook), "cc": "share_copylink",
                    #                            "shareId": "143108986354"})

                    #requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

                    # payload1 = {"operationName": "SharePageQuery",
                    #            "variables": {"photoId": work['id'], "principalId": uid},
                    #            "query": "query SharePageQuery($principalId: String, $photoId: String) {\n  feedById(principalId: $principalId, photoId: $photoId) {\n    currentWork {\n      playUrl\n      __typename\n    }\n    __typename\n  }\n}\n"}
                    # res1 = requests.post(DATA_URL, headers=__headers_web, json=payload1)
                    # html1 = json.loads(res1.content.decode(encoding='utf-8', errors='strict'))['data']['feedById']['currentWork']
                    # v_url = html1['playUrl']

                    html = res.text
                    waitreplace2 = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'
                    v_url2 = re.findall(waitreplace2, html)
                    if v_url2 == []:
                        waitreplace = '"srcNoMark":"(.*?)"},"user"'
                    else:
                        waitreplace = work['id'] + '&#34.*?&#34;srcNoMark&#34;:&#34;(.*?)&#34;'
                    yzm_jici1 = yzm_jici1 + 1
                    if yzm_jici1 == QJ.yzm_num:
                        restart_program()

                        # doufu()

                v_url = re.findall(waitreplace, html)
                # pattern = re.compile(r"playUrl", re.MULTILINE | re.DOTALL)
                # script = soup.find("script", text=pattern)
                # s = pattern.search(script.text).string
                # v_url = s.split('playUrl":"')[1].split('.mp4')[0].encode('utf-8').decode('unicode-escape') + '.mp4'
                try:
                    text.insert(END, "  " + str(wdx) + ")视频作品：" + "丨" + w_time + "丨" + work['id'] + "丨" + w_name)
                    text.update()
                    text.see(END)
                except:
                    text.insert(END, "  这里似乎有点小错误，已跳过")
                    text.update()
                    text.see(END)
                # v_name = w_time + w_index + "_" + w_name + ".mp4"
                v_name = w_time + "_" + work['id'] + "_" + w_name + ".mp4"
                dir2 = dir + "视频/"
                if not os.path.exists(dir2):
                    os.makedirs(dir2)
                # video = dir2 + v_name
                video = dir2 + v_name

                if v_url:
                    if not os.path.exists(video):
                        # r = requests.get(v_url)
                        # r = requests.get(v_url[0])
                        # r.raise_for_status()
                        while True:  # 一直循环，知道访问站点成功
                            try:
                                # 以下except都是用来捕获当requests请求出现异常时，
                                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                                requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                                r = requests.get(v_url[0], verify=False)
                                r.raise_for_status()
                                #res = requests.get(w_url, headers=__headers_mobile, verify=False)
                                #res.raise_for_status()
                                break
                            except requests.exceptions.HTTPError:
                                text.insert(END, "HTTPError, 等待60秒后程序重新运行!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()
                            except requests.exceptions.ConnectionError:
                                text.insert(END, "ConnectionError, 等待60秒后程序重新运行!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()
                            except requests.exceptions.ChunkedEncodingError:
                                text.insert(END, "ChunkedEncodingError, 等待60秒后程序重新运行!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()
                            except:
                                text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                                text.update()
                                text.see(END)
                                time.sleep(60)
                                restart_program()

                        with open(video, "wb") as f:
                            f.write(r.content)
                        text.insert(END, "    视频 " + v_name + " 下载成功 √")
                        text.update()
                        text.see(END)
                        text.insert(END, "视频地址:")
                        text.update()
                        text.see(END)
                        text.insert(END, v_url[0])
                        text.update()
                        text.see(END)
                        text.insert(END, "丨视频下载成功 √丨")
                        text.update()
                        text.see(END)
                    else:
                        text.insert(END, "    视频 " + v_name + " 已存在 √")
                        text.update()
                        text.see(END)
                        text.insert(END, "丨视频已存在 √丨")
                        text.update()
                        text.see(END)
                else:
                    text.insert(END, "未找到视频-----60秒后程序自动重新运行!!!")
                    text.update()
                    text.see(END)
                    time.sleep(60)
                    restart_program()
                    # doufu()
    else:
        text.insert(END, "错误的类型-----60秒后程序自动重新运行!!!")
        text.update()
        text.see(END)
        time.sleep(60)
        restart_program()
        #doufu()


def __read_preset():
    p_path = "uid.txt"
    with open(p_path, "r") as f:
        for line in f:
            if line[0] != "#":
                QJ.doufu_list__.append(line.strip())


def __switch_id(uid):
    payload = {"operationName": "SearchOverviewQuery",
               "variables": {"keyword": uid, "ussid": None},
               "query": "query SearchOverviewQuery($keyword: String, $ussid: String) {\n  pcSearchOverview(keyword: $keyword, ussid: $ussid) {\n    list {\n      ... on SearchCategoryList {\n        type\n        list {\n          categoryId\n          categoryAbbr\n          title\n          src\n          __typename\n        }\n        __typename\n      }\n      ... on SearchUserList {\n        type\n        ussid\n        list {\n          id\n          name\n          living\n          avatar\n          sex\n          description\n          counts {\n            fan\n            follow\n            photo\n            __typename\n          }\n          __typename\n        }\n        __typename\n      }\n      ... on SearchLivestreamList {\n        type\n        lssid\n        list {\n          user {\n            id\n            avatar\n            name\n            __typename\n          }\n          poster\n          coverUrl\n          caption\n          id\n          playUrls {\n            quality\n            url\n            __typename\n          }\n          quality\n          gameInfo {\n            category\n            name\n            pubgSurvival\n            type\n            kingHero\n            __typename\n          }\n          hasRedPack\n          liveGuess\n          expTag\n          __typename\n        }\n        __typename\n      }\n      __typename\n    }\n    __typename\n  }\n}\n"}

    res = requests.post(DATA_URL, headers=__headers_web, json=payload)
    dt = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']
    # with open("data/jj_" + uid + ".json", "w") as fp:
    #     fp.write(json.dumps(dt, indent=2))

    return dt['pcSearchOverview']['list'][1]['list'][0]['id']


def __openchrome():
    if QJ.mdl == 0:
        if QJ.cookie1 == "" and QJ.cookie2 == "" and QJ.cookie3 == "" and QJ.cookie4 == "" and QJ.cookie5 == "":
            if QJ.duanlian_list[0] == "":
                text.insert(END, "请在xhconfig.ini配置文件中填入分享短链!!!")
                text.update()
                text.see(END)
                time.sleep(5)
                root.quit()
            else:
                if len(QJ.duanlian_list) == 1:
                    QJ.duanlian = QJ.duanlian_list[0]
                else:
                    QJ.duanlian = QJ.duanlian_list[random.randint(0, len(QJ.duanlian_list) - 1)]

            QJ.ua_list_ = ua_list[random.randint(0, 28)]
            __headers_mobile['User-Agent'] = QJ.ua_list_
            text.insert(END, "定义浏览器移动端标识(User-Agent):" + QJ.ua_list_)
            text.update()
            text.see(END)
            text.insert(END, "当前选择的分享短链:" + QJ.duanlian)
            text.update()
            text.see(END)
            requests.adapters.DEFAULT_RETRIES = 5
            s = requests.session()
            s.keep_alive = False
            driver = webdriver.Chrome(executable_path="Google Chrome/chromedriver.exe")
            driver.get("https://live.kuaishou.com/v/hot/")
            time.sleep(1)
            if var4.get() == 1:
                driver.maximize_window()
            time.sleep(1)
            # driver.implicitly_wait(30)
            file = '提示音.wav'  # 文件名是完整路径名
            iframes = driver.find_elements_by_tag_name("iframe")
            while iframes != []:
                # driver.implicitly_wait(30)
                text.insert(END, "出现验证码弹窗请手动验证")
                text.update()
                text.see(END)
                pygame.mixer.init()  # 初始化音频
                track = pygame.mixer.music.load(file)  # 载入音乐文件
                pygame.mixer.music.play()  # 开始播放
                time.sleep(3)
                pygame.mixer.music.stop()  # 停止播放
                iframes = driver.find_elements_by_tag_name("iframe")
                if iframes == []:
                    pygame.mixer.music.stop()  # 停止播放
                    break
            name = driver.find_element_by_xpath('//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
            name_title = name.get_attribute('title')
            # cookie= driver.get_cookies()
            while name_title == "":
                text.insert(END, "你还没有登录,请登录!!!")
                text.update()
                text.see(END)
                if var5.get() == 1:
                    time.sleep(1)
                    driver.find_element_by_class_name("tip-container").click()
                    time.sleep(1)
                    driver.find_element_by_class_name("third-part-entry-qq").click()
                    driver.close()
                    time.sleep(3)
                    driver.switch_to.window(driver.window_handles[0])
                    driver.switch_to.frame(0)
                    driver.find_element_by_class_name("nick").click()
                    time.sleep(3)
                    name = driver.find_element_by_xpath(
                        '//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
                    name_title = name.get_attribute('title')
                else:
                    pygame.mixer.init()  # 初始化音频
                    track = pygame.mixer.music.load(file)  # 载入音乐文件
                    pygame.mixer.music.play()  # 开始播放
                    driver.find_element_by_class_name("tip-container").click()
                    time.sleep(20)
                    pygame.mixer.music.stop()  # 停止播放
                    name = driver.find_element_by_xpath(
                        '//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
                    name_title = name.get_attribute('title')
                    driver.refresh()
            text.delete(0, END)
            text.insert(END, "你已经登录,登录名:" + name_title)
            text.update()
            text.see(END)
            cookie = driver.get_cookies()
            # driver.get("https://live.kuaishou.com/u/G338217245/3xjz7rnjnh6hjts")
            cookie = [item['value'] for item in driver.get_cookies()]
            cookie1 = [item['name'] for item in driver.get_cookies()]
            # cookie = [item['name'] + '=' + item['value'] for item in driver.get_cookies()]
            for cookie_jici in range(len(cookie1)):
                if cookie1[cookie_jici] == "did":
                    param_did = cookie[cookie_jici]
                    break
            for cookie_jici2 in range(len(cookie1)):
                if cookie1[cookie_jici2] == "kuaishou.live.web_st":
                    param_did2 = cookie[cookie_jici2]
                    break
            for cookie_jici3 in range(len(cookie1)):
                if cookie1[cookie_jici3] == "kuaishou.live.web_ph":
                    param_did3 = cookie[cookie_jici3]
                    break
            for cookie_jici4 in range(len(cookie1)):
                if cookie1[cookie_jici4] == "kuaishou.live.bfb1s":
                    param_did4 = cookie[cookie_jici4]
                    break
            for cookie_jici5 in range(len(cookie1)):
                if cookie1[cookie_jici5] == "userId":
                    param_did5 = cookie[cookie_jici5]
                    QJ.userid_cook = cookie[cookie_jici5]
                    break
            config = configparser.ConfigParser()
            config.read('.\\xhconfig.ini')
            if config.has_section('cookie') == False:
                config.add_section('cookie')

            config.set('cookie', 'did', str(param_did))
            config.set('cookie', 'kuaishou.live.web_st', str(param_did2))
            config.set('cookie', 'kuaishou.live.web_ph', str(param_did3))
            config.set('cookie', 'kuaishou.live.bfb1s', str(param_did4))
            config.set('cookie', 'userId', str(param_did5))

            o = open('.\\xhconfig.ini', 'w')
            config.write(o)
            o.close()  # 不要忘
            driver.get("https://live.kuaishou.com/v/hot/")
            time.sleep(1)
            # driver.implicitly_wait(30)
            iframes = driver.find_elements_by_tag_name("iframe")
            while iframes != []:
                # driver.implicitly_wait(30)
                text.insert(END, "出现验证码弹窗请手动验证")
                text.update()
                text.see(END)
                pygame.mixer.init()  # 初始化音频
                track = pygame.mixer.music.load(file)  # 载入音乐文件
                pygame.mixer.music.play()  # 开始播放
                time.sleep(3)
                pygame.mixer.music.stop()  # 停止播放
                iframes = driver.find_elements_by_tag_name("iframe")
                if iframes == []:
                    pygame.mixer.music.stop()  # 停止播放
                    break
            driver.close()
            set_did(param_did, param_did2, param_did3, param_did4, param_did5)
        else:
            if QJ.duanlian_list[0] == "":
                text.insert(END, "请在xhconfig.ini配置文件中填入分享短链!!!")
                text.update()
                text.see(END)
                time.sleep(5)
                root.quit()
            else:
                if len(QJ.duanlian_list) == 1:
                    QJ.duanlian = QJ.duanlian_list[0]
                else:
                    QJ.duanlian = QJ.duanlian_list[random.randint(0, len(QJ.duanlian_list) - 1)]

            QJ.ua_list_ = ua_list[random.randint(0, 28)]
            __headers_mobile['User-Agent'] = QJ.ua_list_
            text.insert(END, "定义浏览器移动端标识(User-Agent):" + QJ.ua_list_)
            text.update()
            text.see(END)
            text.insert(END, "当前选择的分享短链:" + QJ.duanlian)
            text.update()
            text.see(END)
            requests.adapters.DEFAULT_RETRIES = 5
            s = requests.session()
            s.keep_alive = False
            param_did = QJ.cookie1
            param_did2 = QJ.cookie2
            param_did3 = QJ.cookie3
            param_did4 = QJ.cookie4
            param_did5 = QJ.cookie5
            set_did(param_did, param_did2, param_did3, param_did4, param_did5)
    else:
        if QJ.duanlian_list[0] == "":
            text.insert(END, "请在xhconfig.ini配置文件中填入分享短链!!!")
            text.update()
            text.see(END)
            time.sleep(5)
            root.quit()
        else:
            if len(QJ.duanlian_list) == 1:
                QJ.duanlian = QJ.duanlian_list[0]
            else:
                QJ.duanlian = QJ.duanlian_list[random.randint(0, len(QJ.duanlian_list) - 1)]

        QJ.ua_list_ = ua_list[random.randint(0, 28)]
        __headers_mobile['User-Agent'] = QJ.ua_list_
        text.insert(END, "定义浏览器移动端标识(User-Agent):" + QJ.ua_list_)
        text.update()
        text.see(END)
        text.insert(END, "当前选择的分享短链:" + QJ.duanlian)
        text.update()
        text.see(END)
        requests.adapters.DEFAULT_RETRIES = 5
        s = requests.session()
        s.keep_alive = False
        driver = webdriver.Chrome(executable_path="Google Chrome/chromedriver.exe")
        driver.get("https://live.kuaishou.com/v/hot/")
        time.sleep(1)
        if var4.get() == 1:
            driver.maximize_window()
        time.sleep(1)
        # driver.implicitly_wait(30)
        file = '提示音.wav'  # 文件名是完整路径名
        iframes = driver.find_elements_by_tag_name("iframe")
        while iframes != []:
            # driver.implicitly_wait(30)
            text.insert(END, "出现验证码弹窗请手动验证")
            text.update()
            text.see(END)
            pygame.mixer.init()  # 初始化音频
            track = pygame.mixer.music.load(file)  # 载入音乐文件
            pygame.mixer.music.play()  # 开始播放
            time.sleep(3)
            pygame.mixer.music.stop()  # 停止播放
            iframes = driver.find_elements_by_tag_name("iframe")
            if iframes == []:
                pygame.mixer.music.stop()  # 停止播放
                break
        name = driver.find_element_by_xpath('//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
        name_title = name.get_attribute('title')
        # cookie= driver.get_cookies()
        while name_title == "":
            text.insert(END, "你还没有登录,请登录!!!")
            text.update()
            text.see(END)
            if var5.get() == 1:
                time.sleep(1)
                driver.find_element_by_class_name("tip-container").click()
                time.sleep(1)
                driver.find_element_by_class_name("third-part-entry-qq").click()
                driver.close()
                time.sleep(3)
                driver.switch_to.window(driver.window_handles[0])
                driver.switch_to.frame(0)
                driver.find_element_by_class_name("nick").click()
                time.sleep(3)
                name = driver.find_element_by_xpath(
                    '//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
                name_title = name.get_attribute('title')
            else:
                pygame.mixer.init()  # 初始化音频
                track = pygame.mixer.music.load(file)  # 载入音乐文件
                pygame.mixer.music.play()  # 开始播放
                driver.find_element_by_class_name("tip-container").click()
                time.sleep(20)
                pygame.mixer.music.stop()  # 停止播放
                name = driver.find_element_by_xpath(
                    '//*[@id="app"]/div[1]/div[1]/header/div/div[2]/div[3]/a/span')
                name_title = name.get_attribute('title')
                driver.refresh()
        text.delete(0, END)
        text.insert(END, "你已经登录,登录名:" + name_title)
        text.update()
        text.see(END)
        cookie = driver.get_cookies()
        # driver.get("https://live.kuaishou.com/u/G338217245/3xjz7rnjnh6hjts")
        cookie = [item['value'] for item in driver.get_cookies()]
        cookie1 = [item['name'] for item in driver.get_cookies()]
        # cookie = [item['name'] + '=' + item['value'] for item in driver.get_cookies()]
        for cookie_jici in range(len(cookie1)):
            if cookie1[cookie_jici] == "did":
                param_did = cookie[cookie_jici]
                break
        for cookie_jici2 in range(len(cookie1)):
            if cookie1[cookie_jici2] == "kuaishou.live.web_st":
                param_did2 = cookie[cookie_jici2]
                break
        for cookie_jici3 in range(len(cookie1)):
            if cookie1[cookie_jici3] == "kuaishou.live.web_ph":
                param_did3 = cookie[cookie_jici3]
                break
        for cookie_jici4 in range(len(cookie1)):
            if cookie1[cookie_jici4] == "kuaishou.live.bfb1s":
                param_did4 = cookie[cookie_jici4]
                break
        for cookie_jici5 in range(len(cookie1)):
            if cookie1[cookie_jici5] == "userId":
                param_did5 = cookie[cookie_jici5]
                QJ.userid_cook = cookie[cookie_jici5]
                break
        config = configparser.ConfigParser()
        config.read('.\\xhconfig.ini')
        if config.has_section('cookie') == False:
            config.add_section('cookie')

        config.set('cookie', 'did', str(param_did))
        config.set('cookie', 'kuaishou.live.web_st', str(param_did2))
        config.set('cookie', 'kuaishou.live.web_ph', str(param_did3))
        config.set('cookie', 'kuaishou.live.bfb1s', str(param_did4))
        config.set('cookie', 'userId', str(param_did5))

        o = open('.\\xhconfig.ini', 'w')
        config.write(o)
        o.close()  # 不要忘
        driver.get("https://live.kuaishou.com/v/hot/")
        time.sleep(1)
        # driver.implicitly_wait(30)
        iframes = driver.find_elements_by_tag_name("iframe")
        while iframes != []:
            # driver.implicitly_wait(30)
            text.insert(END, "出现验证码弹窗请手动验证")
            text.update()
            text.see(END)
            pygame.mixer.init()  # 初始化音频
            track = pygame.mixer.music.load(file)  # 载入音乐文件
            pygame.mixer.music.play()  # 开始播放
            time.sleep(3)
            pygame.mixer.music.stop()  # 停止播放
            iframes = driver.find_elements_by_tag_name("iframe")
            if iframes == []:
                pygame.mixer.music.stop()  # 停止播放
                break
        driver.close()
        set_did(param_did, param_did2, param_did3, param_did4, param_did5)


def restart_program():  # 重启程序
    if QJ.zhuangtaima != "":
        loginout()
        python = sys.executable
        os.execl(python, python, *sys.argv)
    else:
        python = sys.executable
        os.execl(python, python, *sys.argv)



def __intro():
    thread_it(__openchrome())

def __intro2():
    thread_it(login())

def thread_it(func, *args):
    '''将函数打包进线程'''
    # 创建
    t = threading.Thread(target=func, args=args)
    # 守护 !!!
    t.setDaemon(True)
    # 启动
    t.start()
    # 阻塞--卡死界面！
    # t.join()

def one_click_access():
    global click_access
    click_access = 1
    thread_it(__init__, )


def one_click_access2():
    page = 1
    if not os.path.exists("uid.txt"):
        open("uid.txt", "w")
    payload = {"operationName": "FollowQuery",
               "variables": {"count": 999,"pcursor":""},
               "query": "query FollowQuery($pcursor: String, $count: Int) {\n  allFollows(pcursor: $pcursor, count: $count) {\n    list {\n      id\n      name\n      living\n      avatar\n      sex\n      description\n      counts {\n        fan\n        follow\n        photo\n        __typename\n      }\n      __typename\n    }\n    pcursor\n    __typename\n  }\n}\n"}
    # payload = {"operationName": "privateFeedsQuery",
    #            "variables":{"principalId":uid,"pcursor":"","count":99999},
    #            "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
    res = requests.post(DATA_URL, headers=__headers_web, json=payload)

    works = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['allFollows']['list']
    pcursor = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['allFollows']['pcursor']
    text.insert(END, '第%s页uid获取成功\n' % (page))
    text.update()
    text.see(END)

    page += 1
    payload = {"operationName": "FollowQuery",
               "variables": {"count": 999, "pcursor": 1017},
               "query": "query FollowQuery($pcursor: String, $count: Int) {\n  allFollows(pcursor: $pcursor, count: $count) {\n    list {\n      id\n      name\n      living\n      avatar\n      sex\n      description\n      counts {\n        fan\n        follow\n        photo\n        __typename\n      }\n      __typename\n    }\n    pcursor\n    __typename\n  }\n}\n"}
    # payload = {"operationName": "privateFeedsQuery",
    #            "variables":{"principalId":uid,"pcursor":"","count":99999},
    #            "query": "query privateFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\n  privateFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\n    pcursor\n    list {\n      id\n      thumbnailUrl\n      poster\n      workType\n      type\n      useVideoPlayer\n      imgUrls\n      imgSizes\n      magicFace\n      musicName\n      caption\n      location\n      liked\n      onlyFollowerCanComment\n      relativeHeight\n      timestamp\n      width\n      height\n      counts {\n        displayView\n        displayLike\n        displayComment\n        __typename\n      }\n      user {\n        id\n        eid\n        name\n        avatar\n        __typename\n      }\n      expTag\n      __typename\n    }\n    __typename\n  }\n}\n"}
    res1 = requests.post(DATA_URL, headers=__headers_web, json=payload)
    works = works + json.loads(res1.content.decode(encoding='utf-8', errors='strict'))['data']['allFollows']['list']
    pcursor = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['data']['allFollows']['pcursor']
    text.insert(END, '第%s页uid获取成功\n' % (page))
    text.update()
    text.see(END)


    works_uid = works
    gz_list = len(works_uid)
    gz_text = open("uid.txt", "w+")
    gz_text.truncate(0)
    text.insert(END, "正在获取uid中,请稍等..." )
    text.update()
    text.see(END)
    for gz in range(len(works_uid)):
        gz_text.write(str(works_uid[gz]['id']) + "\n")
    gz_text.close()
    text.insert(END, "获取并写入uid.txt成功..." )
    text.update()
    text.see(END)
    new_down = tkinter.messagebox.askokcancel('提示', '你是否要重新开始从头下载!!!')
    if new_down == True:
        save_config_jb3()
    else:
        tkinter.messagebox.showinfo('提示', '看来你不愿意重新重头开始下载!')

def stop():
    """Stop scanning by setting the global flag to False."""
    QJ.stop = True
    text.insert(END, "正在跳过当前用户...")
    text.update()
    text.see(END)

def save_config_jb():
    config = configparser.ConfigParser()
    config.read('.\\xhconfig.ini')
    if config.has_section('基本设置') == False:
        config.add_section('基本设置')


    config.set('基本设置','自动模式',str(var2.get()))
    config.set('基本设置', '免登录', str(var8.get()))
    config.set('基本设置','延时',entry.get())
    # config.set('基本设置', '已存在次数', entry2.get())
    # config.set('基本设置', '自动跳过', str(var.get()))
    config.set('基本设置', '浏览器最大化', str(var4.get()))
    config.set('基本设置', '使用QQ登录', str(var5.get()))
    config.set('基本设置', '只下载视频', str(var7.get()))
    config.set('基本设置', '只下载图集', str(var3.get()))
    # config.set('基本设置', '单卡卡密自动登录', str(var6.get()))
    # config.set('基本设置', '单卡卡密', dkkmbjk.get())


    o = open('.\\xhconfig.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭
    tkinter.messagebox.showinfo('提示', '保存配置后软件自动重启!!!')
    time.sleep(1)
    restart_program()


def save_config_jb2():
    config = configparser.ConfigParser()
    config.read('.\\xhconfig.ini')
    if config.has_section('用户日志') == False:
        config.add_section('用户日志')

    config.set('用户日志', '当前uid', QJ.current_uid)
    config.set('用户日志', '当前解析视频数', str(QJ.video_num))

    o = open('.\\xhconfig.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭


def save_config_jb3():
    config = configparser.ConfigParser()
    config.read('.\\xhconfig.ini')
    if config.has_section('用户日志') == False:
        config.add_section('用户日志')

    config.set('用户日志', '当前uid', "0")
    config.set('用户日志', '当前解析视频数', "0")

    o = open('.\\xhconfig.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭
    tkinter.messagebox.showinfo('提示', '保存配置后软件自动重启!!!')
    time.sleep(1)
    restart_program()

def save_config_jb4():
    config = configparser.ConfigParser()
    config.read('.\\xhconfig.ini')
    if config.has_section('用户日志') == False:
        config.add_section('用户日志')

    config.set('用户日志', '当前解析视频数', "0")

    o = open('.\\xhconfig.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭
    tkinter.messagebox.showinfo('提示', '保存配置后软件自动重启!!!')
    time.sleep(1)
    restart_program()

def login():
    if dkkmbjk.get() != "":
        QJ.dkkm = dkkmbjk.get()
        QJ.jiqima = jiqimabjk.get()
        payload = {"SingleCode": QJ.dkkm,
                   "Ver": "1.0",
                   "Mac": QJ.jiqima}
        #res = requests.post("http://w.eydata.net/521270375f95bba8", payload, verify=False)
        while True:  # 一直循环，知道访问站点成功
            try:
                # 以下except都是用来捕获当requests请求出现异常时，
                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                res = requests.post("http://w.eydata.net/521270375f95bba8", payload, verify=False)
                res.raise_for_status()
                # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                # res.raise_for_status()
                break
            except requests.exceptions.HTTPError:
                text.insert(END, "HTTPError, 等待5秒后重新尝试登录!!!")
                text.update()
                text.see(END)
                time.sleep(5)
            except requests.exceptions.ConnectionError:
                text.insert(END, "ConnectionError, 等待5秒后重新尝试登录!!!")
                text.update()
                text.see(END)
                time.sleep(5)
            except requests.exceptions.ChunkedEncodingError:
                text.insert(END, "ChunkedEncodingError, 等待5秒后重新尝试登录!!!")
                text.update()
                text.see(END)
                time.sleep(5)
            except:
                text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待5秒后重新尝试登录!!!")
                text.update()
                text.see(END)
                time.sleep(5)
        if len(res.text) == 32:
            text.insert(END, "登录成功!!!")
            text.update()
            text.see(END)
            QJ.zhuangtaima = res.text
            config = configparser.ConfigParser()
            config.read('.\\xhconfig.ini')
            if config.has_section('基本设置') == False:
                config.add_section('基本设置')

            config.set('基本设置', '单卡卡密', str(QJ.dkkm))
            config.set('基本设置', '状态码', str(QJ.zhuangtaima))

            o = open('.\\xhconfig.ini', 'w')
            config.write(o)
            o.close()  # 不要忘记关闭
            if var2.get() == 1:
                __openchrome()
            # master.destroy()
            # root.wm_attributes("-topmost", 1)
            # time.sleep(1)
            # root.wm_attributes("-topmost", 0)
        else:
            if var6.get() != 1:
                text.insert(END, "登录失败!!!错误代码:" + res.text)
                text.update()
                text.see(END)
            else:
                while len(res.text) != 32:
                    QJ.dkkm = dkkmbjk.get()
                    QJ.jiqima = jiqimabjk.get()
                    #print(QJ.dkkm)
                    #print(QJ.jiqima)
                    payload = {"SingleCode": QJ.dkkm,
                               "Ver": "1.0",
                               "Mac": QJ.jiqima}
                    #res = requests.post("http://w.eydata.net/521270375f95bba8", payload)
                    while True:  # 一直循环，知道访问站点成功
                        try:
                            # 以下except都是用来捕获当requests请求出现异常时，
                            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                            res = requests.post("http://w.eydata.net/521270375f95bba8", payload, verify=False)
                            res.raise_for_status()
                            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                            # res.raise_for_status()
                            break
                        except requests.exceptions.HTTPError:
                            text.insert(END, "HTTPError, 等待5秒后重新尝试登录!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ConnectionError:
                            text.insert(END, "ConnectionError, 等待5秒后重新尝试登录!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except requests.exceptions.ChunkedEncodingError:
                            text.insert(END, "ChunkedEncodingError, 等待5秒后重新尝试登录!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                        except:
                            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待5秒后重新尝试登录!!!")
                            text.update()
                            text.see(END)
                            time.sleep(5)
                    if len(res.text) == 32:
                        text.insert(END, "登录成功!!!")
                        text.update()
                        text.see(END)
                        QJ.zhuangtaima = res.text
                        config = configparser.ConfigParser()
                        config.read('.\\xhconfig.ini')
                        if config.has_section('基本设置') == False:
                            config.add_section('基本设置')

                        config.set('基本设置', '单卡卡密', dkkmbjk.get())

                        o = open('.\\xhconfig.ini', 'w')
                        config.write(o)
                        o.close()  # 不要忘记关闭
                        # master.destroy()
                        # root.wm_attributes("-topmost", 1)
                        # time.sleep(1)
                        # root.wm_attributes("-topmost", 0)
                    else:
                        text.insert(END, "登录失败,5秒后重试!!!错误代码:" + res.text)
                        text.update()
                        text.see(END)
                        time.sleep(5)
    else:
        tkinter.messagebox.showinfo('提示', '请输入单卡卡密!!!')







def jiqimazhuanbang():
    QJ.dkkm = dkkmbjk.get()
    QJ.jiqima = jiqimabjk.get()
    #print(QJ.dkkm)
    #print(QJ.jiqima)
    payload = {"UserName": QJ.dkkm,
               "UserPwd": "",
               "Mac": QJ.jiqima,
               "Type":""}

    #res = requests.post("http://w.eydata.net/32481283946216a7",payload)
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
            res = requests.post("http://w.eydata.net/32481283946216a7", payload, verify=False)
            res.raise_for_status()
            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
            # res.raise_for_status()
            break
        except requests.exceptions.HTTPError:
            text.insert(END, "HTTPError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except requests.exceptions.ConnectionError:
            text.insert(END, "ConnectionError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except requests.exceptions.ChunkedEncodingError:
            text.insert(END, "ChunkedEncodingError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except:
            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
    if res.text == "1":
        text.insert(END, "机器码换绑成功!!!")
        text.update()
        text.see(END)
    else:
        text.insert(END, "机器码换绑失败!!!错误代码:" + res.text)
        text.update()
        text.see(END)

def ipmazhuanbang():
    QJ.dkkm = dkkmbjk.get()
    QJ.jiqima = jiqimabjk.get()
    #print(QJ.dkkm)
    #print(QJ.jiqima)
    payload = {"SingleCode": QJ.dkkm}

    # res = requests.post("http://w.eydata.net/32481283946216a7",payload)
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
            res = requests.post("http://w.eydata.net/51f0cf1ffba45b7d", payload, verify=False)
            res.raise_for_status()
            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
            # res.raise_for_status()
            break
        except requests.exceptions.HTTPError:
            text.insert(END, "HTTPError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except requests.exceptions.ConnectionError:
            text.insert(END, "ConnectionError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except requests.exceptions.ChunkedEncodingError:
            text.insert(END, "ChunkedEncodingError, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
        except:
            text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待5秒后重新尝试登录!!!")
            text.update()
            text.see(END)
            time.sleep(5)
    if res.text == "1":
        text.insert(END, "ip换绑成功!!!")
        text.update()
        text.see(END)
    else:
        text.insert(END, "ip换绑失败!!!错误代码:" + res.text)
        text.update()
        text.see(END)

def loginout():
    QJ.dkkm = dkkmbjk.get()
    payload = {"StatusCode": QJ.zhuangtaima,
               "UserName": QJ.dkkm}
    res = requests.post("http://w.eydata.net/129cbfe8e3694512",payload)
    if res.text == "1":
        text.insert(END, "成功退出登录!!!")
        text.update()
        text.see(END)

def loginout2():
    QJ.dkkm = dkkmbjk.get()
    config = configparser.ConfigParser()
    config.read('.\\xhconfig.ini')
    config.items('基本设置')
    tuichu_zhuangtaima = config.get('基本设置', '状态码')
    if tuichu_zhuangtaima == "":
        tkinter.messagebox.showinfo('提示', '你还没有登录!!!')
    else:
        payload = {"StatusCode": tuichu_zhuangtaima,
                   "UserName": QJ.dkkm}
        res = requests.post("http://w.eydata.net/129cbfe8e3694512", payload)
    if res.text == "1":
        text.insert(END, "成功退出登录!!!")
        text.update()
        text.see(END)
        time.sleep(5)

def on_closing():
    if messagebox.askokcancel("提示", "是否要退出软件?"):
        if QJ.zhuangtaima != "":
            loginout()
            root.quit()
        else:
            root.quit()


root = Tk()   #生成一个主窗口对象
root.title('奥利给丶快手喜欢批量下载助手V1.0 正式版(暂时稳定)') #标题
width = 579
height = 822
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth-width)/2, (screenheight-height)/2)
root.geometry(alignstr)
root.resizable(width=False, height=True)
#root.geometry('672x822+600+100') #大小位置
root.protocol('WM_DELETE_WINDOW', on_closing)
#webbrowser.open_new_tab("http://zanzhu.xiaobb.club/")

if not os.path.exists('.\\xhconfig.ini'):
    open('.\\xhconfig.ini', "w")
if not os.path.getsize('.\\xhconfig.ini'):
    config = configparser.ConfigParser()
    config.read('.\\xhconfig.ini')
    if config.has_section('基本设置') == False:
        config.add_section('基本设置')
        config.set('基本设置', '自动模式', "0")
        config.set('基本设置', '免登录', "0")
        config.set('基本设置', '延时', "1")
        # config.set('基本设置', '已存在次数', "20")
        # config.set('基本设置', '自动跳过', "0")
        config.set('基本设置', '验证码出现次数', "20")
        config.set('基本设置', '浏览器最大化', "0")
        config.set('基本设置', '使用QQ登录', "0")
        config.set('基本设置', '只下载视频', "0")
        config.set('基本设置', '只下载图集', "0")
        config.set('基本设置', '分享的短链', '')

    if config.has_section('cookie') == False:
        config.add_section('cookie')
        config.set('cookie', 'did', "")
        config.set('cookie', 'kuaishou.live.web_st', "")
        config.set('cookie', 'kuaishou.live.web_ph', "")
        config.set('cookie', 'kuaishou.live.bfb1s', "")
        config.set('cookie', 'userId', "")
    o = open('.\\xhconfig.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭

#-------------------------------------分割线

config = configparser.ConfigParser()
config.read('.\\xhconfig.ini')

# print('sections:', ' ', config.sections())
#
# # -options(section)得到该section的所有option
# print('options:', ' ', config.options('config'))
#
# # -items（section）得到该section的所有键值对
# print('items:', ' ', config.items('cmd'))
#
# # -get(section,option)得到section中option的值，返回为string类型
# print('get:', ' ', config.get('cmd', 'startserver'))
#
# # -getint(section,option)得到section中的option的值，返回为int类型
# print('getint:', ' ', config.getint('cmd', 'id'))
# print('getfloat:', ' ', config.getfloat('cmd', 'weight'))
# print('getboolean:', '  ', config.getboolean('cmd', 'isChoice'))
# """
# 首先得到配置文件的所有分组，然后根据分组逐一展示所有
# """
#
# for sections in config.sections():
#     for items in config.items(sections):
#         print(items)

config.items('基本设置')
QJ.cookie1 = config.get('cookie', 'did')
QJ.cookie2 = config.get('cookie', 'kuaishou.live.web_st')
QJ.cookie3 = config.get('cookie', 'kuaishou.live.web_ph')
QJ.cookie4 = config.get('cookie', 'kuaishou.live.bfb1s')
QJ.cookie5 = config.get('cookie', 'userId')



text = Listbox(root,width=82,height=30)
text.grid(row=0,columnspan=3, sticky=W)

# button=Button(root,text="1.初始",width=10,command=lambda :thread_it(__init__, ))
# button.grid(row=5,column=0,sticky=W)

duanlian_list = config.get('基本设置', '分享的短链')
QJ.duanlian_list = duanlian_list.split('丨')

# jiqimabq = Label(root, text='机器码:')
# jiqimabq.place(x=15,y=545)
#
# jiqimabjk = Entry(root, width=40)
# jiqimabjk.place(x=60,y=545)
# jiqimabjk.insert(0, config.get('基本设置', '机器码'))
# jiqima = config.get('基本设置', '机器码')
# QJ.jiqima = jiqima
#
# dkkmbq = Label(root, text='单卡卡密:')
# dkkmbq.place(x=2,y=575)
#
# dkkmbjk = Entry(root, width=40)
# dkkmbjk.place(x=60,y=575)
# dkkm = config.get('基本设置', '单卡卡密')
# if dkkm != "":
#     dkkmbjk.insert(0, config.get('基本设置', '单卡卡密'))
#     QJ.dkkm = dkkmbjk.get()
#
#
# dkkmban = Button(root, text="登录", width=8, command=lambda :thread_it(login, ))  # ,command=lambda :thread_it(one_click_access, )
# dkkmban.place(x=350,y=545)
#
# dkkman2 = Button(root, text="机器码转绑", width=8, command=lambda :thread_it(jiqimazhuanbang, ))  # ,command=lambda :thread_it(one_click_access, )
# dkkman2.place(x=430,y=545)
#
# dkkmban3 = Button(root, text="ip转绑", width=8, command=lambda :thread_it(ipmazhuanbang, ))  # ,command=lambda :thread_it(one_click_access, )
# dkkmban3.place(x=510,y=545)
#
# dkkmban4 = Button(root, text="退出登录", width=10, command=lambda :thread_it(loginout2, ))  # ,command=lambda :thread_it(one_click_access, )
# dkkmban4.place(x=370,y=745)

var2 = IntVar()
Checkbutton2 = Checkbutton(root,text="自动模式",  variable=var2)
Checkbutton2.place(x=15,y=615)
if config.getint('基本设置', '自动模式') == 1:
    Checkbutton2.select()
    thread_it(__init__, )

var8 = IntVar()
Checkbutton8 = Checkbutton(root,text="免登陆",  variable=var8)
Checkbutton8.place(x=15,y=645)
if config.getint('基本设置', '免登录') == 1:
    Checkbutton8.select()
    QJ.mdl = 1

var4 = IntVar()
Checkbutton4 = Checkbutton(root,text="浏览器最大化",  variable=var4)
Checkbutton4.place(x=15,y=705)
if config.getint('基本设置', '浏览器最大化') == 1:
    Checkbutton4.select()

var5 = IntVar()
Checkbutton5 = Checkbutton(root,text="使用QQ登录",  variable=var5)
Checkbutton5.place(x=15,y=675)
if config.getint('基本设置', '使用QQ登录') == 1:
    Checkbutton5.select()

var7 = IntVar()
Checkbutton7 = Checkbutton(root,text="只下载视频",  variable=var7)
Checkbutton7.place(x=150,y=645)
if config.getint('基本设置', '只下载视频') == 1:
    Checkbutton7.select()

var3 = IntVar()
Checkbutton3 = Checkbutton(root,text="只下载图集",  variable=var3)
Checkbutton3.place(x=150,y=675)
if config.getint('基本设置', '只下载图集') == 1:
    Checkbutton3.select()

# var6 = IntVar()
# Checkbutton6 = Checkbutton(root,text="单卡卡密自动登录",  variable=var6)
# Checkbutton6.place(x=350,y=575)
# if config.getint('基本设置', '单卡卡密自动登录') == 1:
#     Checkbutton6.select()
#     thread_it(login, )

button5=Button(root,text="保存配置",width=10,command=lambda :thread_it(save_config_jb, ))
button5.place(x=480,y=545)

# button6=Button(root,text="视频从新开始",width=10,command=lambda :thread_it(save_config_jb4, ))
# button6.place(x=175,y=545)

# button7=Button(root,text="全部重新开始",width=10,command=lambda :thread_it(save_config_jb3, ))
# button7.place(x=325,y=545)

label = Label(root,text='延时时间:')
label.place(x=280,y=647)

entry = Entry(root,width=10)
entry.place(x=340,y=647)
entry.insert(0,config.get('基本设置', '延时'))

yichuxiancishu = Label(root, text='已出现次数')
yichuxiancishu.place(x=100,y=615)

# label2 = Label(root,text='出现次数:')
# label2.place(x=280,y=677)

# entry2 = Entry(root,width=10)
# entry2.place(x=340,y=677)
# entry2.insert(0,config.get('基本设置', '已存在次数'))

# var = IntVar()
# Checkbutton = Checkbutton(root,text="自动跳过当前",  variable=var)
# Checkbutton.place(x=450,y=675)
# if config.getint('基本设置', '自动跳过') == 1:
#     Checkbutton.select()

QJ.yzm_num = int(config.get('基本设置', '验证码出现次数'))
#读取用户log配置保存到class全局变量
# QJ.current_uid = config.get('用户日志', '当前uid')
# QJ.video_num = int(config.get('用户日志', '当前解析视频数'))

# button4=Button(root,text="一键跳过当前",width=10,command=lambda :thread_it(stop, ))
# button4.place(x=455,y=645)

# button1=Button(root,text="一键获取uid",width=10,command=lambda :thread_it(one_click_access, ))
# button1.place(x=20,y=545)

button1=Button(root,text="开始",width=10,command=lambda :thread_it(__init__, ))
button1.place(x=20,y=545)

button2=Button(root,text="退出",width=10,command=on_closing)
button2.place(x=250,y=545)


# master = tkinter.Toplevel()  # 生成一个主窗口对象
# #master.attributes("-toolwindow", 1)
# master.wm_attributes("-topmost", 1)
# master.title('奥利给丶快手批量下载助手登录窗口')  # 标题
# master.geometry('416x109+700+300')  # 大小位置
#
# jiqimabq = Label(master, text='机器码:')
# jiqimabq.grid(row=0, sticky=W)
#
# jiqimabjk = Entry(master, width=40)
# jiqimabjk.grid(row=0, column=1, sticky=W)
# jiqimabjk.insert(0, config.get('基本设置', '机器码'))
#
# dkkmbq = Label(master, text='单卡卡密:')
# dkkmbq.grid(row=1, sticky=W)
#
# dkkmbjk = Entry(master, width=40)
# dkkmbjk.grid(row=1, column=1, sticky=W)
# dkkm = config.get('基本设置', '机器码')
# if dkkm != "":
#     dkkmbjk.insert(0, config.get('基本设置', '单卡卡密'))
#
# dkkmban = Button(master, text="登录", width=8, command=lambda :thread_it(login, ))  # ,command=lambda :thread_it(one_click_access, )
# dkkmban.grid(row=3, column=0, sticky=W)
#
# dkkman2 = Button(master, text="机器码转绑", width=8)  # ,command=lambda :thread_it(one_click_access, )
# dkkman2.grid(row=3, column=1)
#
# dkkmban3 = Button(master, text="ip转绑", width=8)  # ,command=lambda :thread_it(one_click_access, )
# dkkmban3.grid(row=3, column=2, sticky=E)

root.mainloop()